package edu.cuit.avatar.thread;

import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author <a href="mailto:1020zhaodan@163.com">Adan</a>
 * @version 1.0
 * @date 2025/7/16 10:47
 */
public class AccountWithLock {
    //公共账户(同一账户):共享资源
    private static Account account = new Account();

    public static void main(String[] args) {
        var executor = Executors.newCachedThreadPool();
        for(var i = 0; i < 100; i++){
            executor.execute(new DepositTask());
        }

        //关闭线程池,不再接收新的任务
        executor.shutdown();
        //等待线程池中所有的任务执行完毕
        while(!executor.isTerminated());

        //输出账户余额
        System.out.println(account.getBalance());
    }

    /**
     * 存款任务
     */
    private static class DepositTask implements Runnable{
        @Override
        public void run() {
            account.deposit(1);
        }
    }

    /**
     * 账户类
     */
    private static class Account{
        private Lock lock = new ReentrantLock(true);
        //账户余额
        private int balance = 0;

        public int getBalance() {
            return balance;
        }

        /**
         * 向账户存款
         * @param amount 存款金额
         */
        public void deposit(int amount){
            //balance += amount; //balance = balance + amount
            lock.lock();
            try {
                int newBalance = balance + amount;
                //模拟存款花费时间：100ms(让出cpu执行时间)
                Thread.sleep(10);
                balance = newBalance;
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                lock.unlock();
            }
        }
    }
}
